package com.example.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign远程调用的拦截器，防止Feign远程调用丢失请求头
 * feign在远程调用之前要构造一个新的请求，调用很多的拦截器 RequestInterceptor interceptor:requestIntercptor
 * 如果有请求头就会加入
 * 新的请求，因此我们这里构造一个拦截器加入请求头
 */
@Configuration
public class MallFeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //拿到当前请求的请求属性
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest(); //老请求
                    if (request!=null){
                        String cookie = request.getHeader("Cookie");
                        //给新请求同步老请求的请求头信息，这里是cooKie
                        requestTemplate.header("Cookie",cookie);
                    }

                }


            }
        };
    }
}
